package com.example.lovewordsapplication.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.util.Patterns;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.example.lovewordsapplication.MyApplication;
import com.example.lovewordsapplication.R;
import com.example.lovewordsapplication.base.BaseActivity;
import com.example.lovewordsapplication.entity.UserInfo;
import com.example.lovewordsapplication.utils.CommonUtil;
import com.example.lovewordsapplication.utils.ErrorCodeUtil;
import com.example.lovewordsapplication.utils.ToastUtil;
import com.google.android.material.checkbox.MaterialCheckBox;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;

import java.util.regex.Pattern;

import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.helper.ErrorCode;
import cn.bmob.v3.listener.SaveListener;

/**
 * 注册账号
 *
 * @author Leung
 * @date 2020/4/7 23:37
 */
public class RegisterActivity extends BaseActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {

    private EditText etEmail;
    private EditText etUserName;
    private EditText etPassword;
    private EditText etConfirmPassword;
    private MaterialCheckBox cb_notice;

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_register;
    }

    @Override
    protected String setTitle() {
        return "注册";
    }

    @Override
    protected boolean isShowBack() {
        return true;
    }

    /**
     * 初始化控件
     */
    @Override
    protected void initView() {
        etEmail = (EditText) findViewById(R.id.et_email);
        etUserName = (EditText) findViewById(R.id.et_username);
        etPassword = (EditText) findViewById(R.id.et_password);
        etConfirmPassword = (EditText) findViewById(R.id.et_confirmPassword);
        Button btnRegister = (Button) findViewById(R.id.btn_register);
        cb_notice = findViewById(R.id.cb_notice);

        cb_notice.setOnCheckedChangeListener(this);
        btnRegister.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (!cb_notice.isChecked()) {
            AlertDialog dialog = new MaterialAlertDialogBuilder(RegisterActivity.this)
                    .setTitle("注意")
                    .setMessage("在注册账号前，请阅读用户注册协议")
                    .setCancelable(false)
                    .setPositiveButton("确定", ((d, w) -> d.dismiss()))
                    .show();
        } else {
            submit();
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            AlertDialog dialog = new MaterialAlertDialogBuilder(RegisterActivity.this)
                    .setTitle("注册协议")
                    .setMessage(CommonUtil.getRawFile(getResources().openRawResource(R.raw.notice)))
                    .setCancelable(false)
                    .setPositiveButton("我已了解", ((d, w) -> d.dismiss()))
                    .show();
        }
    }

    /**
     * 提交注册
     */
    private void submit() {
        // 验证邮箱
        String email = etEmail.getText().toString().trim();
        if (TextUtils.isEmpty(email)) {
            toast("邮箱不能为空");
            return;
        } else if (!isEmail(email)) {
            toast("邮箱格式错误");
            return;
        }
        // 验证用户名
        String userName = etUserName.getText().toString().trim();
        if (TextUtils.isEmpty(userName)) {
            toast("用户名不能为空");
            return;
        }
        // 验证密码
        String password = etPassword.getText().toString().trim();
        if (TextUtils.isEmpty(password)) {
            toast("密码不能为空");
            return;
        } else if (password.length() < 6) {
            toast("密码长度要大于等6位数喔！");
            return;
        }
        // 验证确认密码
        String confirmPassword = etConfirmPassword.getText().toString().trim();
        if (TextUtils.isEmpty(confirmPassword)) {
            toast("确认密码不能为空");
            return;
        } else if (!confirmPassword.equals(password)) {
            toast("两次密码不一致");
            return;
        }

        // 注册
        UserInfo user = new UserInfo();
        user.setUsername(userName);
        user.setEmail(email);
        user.setPassword(password);
        user.setEmailVerified(false);
        user.signUp(new SaveListener<UserInfo>() {
            @Override
            public void done(UserInfo userInfo, BmobException e) {
                // 是否注册成功
                if (e == null) {
                    ToastUtil.showToast(RegisterActivity.this, "注册成功", 0);
                    Intent intent = new Intent();
                    intent.putExtra("username", userName);
                    setResult(RESULT_OK, intent);
                    finish();
                } else {
                    ErrorCodeUtil.getErrorMessage(e.getErrorCode(), MyApplication.getInstance().getContext());
                }
            }
        });

    }

    /**
     * 验证是否是正确的邮箱
     *
     * @param email 邮箱地址
     * @return 是否正确
     */
    private boolean isEmail(String email) {
        String regex = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern pattern = Pattern.compile(regex);
        return pattern.matcher(email).matches();
    }
}
